import React, { useEffect, useState, forwardRef, useRef } from 'react';
import { connect } from 'dva';
import { Button, Table } from 'antd';
import deLedgerCn from 'columns/deviceLedger';
import router from 'umi/router';
import Paging from 'components/common/paging';
import HeadForm from './components/headForm';
import DeclareFault from './components/declareFault';
import MessageModel from 'components/common/MessageModel';
import withRouter from 'umi/withRouter';
import KeepAlive from 'react-activation';
import { ledgerDel, ledgerStop, ledgerOpen, ledgerRmFault } from 'dic/messageModel';

import './index.styl';

const HeadFormRef = forwardRef((props, ref) => (
  <HeadForm {...props} cRef={ref} />
));

function DeviceLedger({
  dispatch,
  deviceLedger: { list, total, pageCount, allPages, serachParams },
  location: { params = {}, pathname },
  commonAction: { catchObj }
}) {
  const searchRef = useRef()
  const { ledgerStatus, runStatus, isRefresh = false } = params;
  const [visible, setVisible] = useState(false);
  const [proId, setProId] = useState(false);
  const [current] = useState(pageCount || 1);
  const [size] = useState(10);
  // 添加序号
  deLedgerCn.list[0].render = (t, r, i) => (pageCount - 1) * 10 + i + 1;
  deLedgerCn.list[deLedgerCn.list.length - 2].render = (t, r) => (r.ledgerStatus === 3 ? r.runStatusStr : '--');
  // 添加操作
  deLedgerCn.list[deLedgerCn.list.length - 1].render = t => (
    <>
      {t.ledgerStatus === 1 && t.userNameIsEqual ? (
        <span className="td-blue" onClick={() => toDetail(t)}>
          审批
        </span>
      ) : null}
      {t.ledgerStatus !== 3 ? (
        <span className="td-blue" onClick={() => toEdit(t)}>
          编辑
        </span>
      ) : null}
      {/* 删除 */}
      {t.ledgerStatus !== 3 ? (
        <MessageModel
          data={ledgerDel}
          handleClick={() => {
            dispatch({
              type: 'deviceLedger/delList',
              payload: {
                id: t.id
              },
            })
            searchRef.current.resetFields()
          }}
        />
      ) : null}
      {/* 停用 */}
      {t.ledgerStatus === 3 ? (
        <MessageModel
          data={ledgerStop}
          handleClick={() => {
            dispatch({
              type: 'deviceLedger/deviceStopOrOpen',
              payload: {
                id: t.id,
                ledgerStatus: 4
              },
            });
            searchRef.current.resetFields()
          }}
        />
      ) : null}
      {/* 启用 */}
      {t.ledgerStatus === 4 ? (
        <MessageModel
          data={ledgerOpen}
          handleClick={() => {
            dispatch({
              type: 'deviceLedger/deviceStopOrOpen',
              payload: {
                id: t.id,
                ledgerStatus: 3
              },
            });
            searchRef.current.resetFields()
          }}
        />
      ) : null}
      {t.ledgerStatus === 3 && t.runStatus === 1 ? (
        <span
          className="td-blue"
          onClick={() => {
            setVisible(true);
            setProId(t.id);
          }}
        >
          申报故障
        </span>
      ) : null}
      {/* 解除故障 */}
      {t.ledgerStatus === 3 && t.runStatus === 2 ? (
        <MessageModel
          data={ledgerRmFault}
          handleClick={() => {
            dispatch({
              type: 'deviceLedger/delFalut',
              payload: {
                contnet: {
                  id: t.id,
                  runStatus: 1
                }
              },
            });
            searchRef.current.resetFields()
          }}
        />
      ) : null}

      <span className="td-blue" onClick={() => toDetail(t)}>
        查看详情
      </span>
    </>
  );
  useEffect(() => {
    dispatch({
      type: 'commonAction/uploadCatch',
      payload: {
        catchObj: {
          deviceLedger: [true, false]
        }
      }
    })
    return function cleanUp() {
      const nowPage = JSON.parse(localStorage.getItem('panes')).find(item => item.key === pathname)
      if (nowPage === undefined) {
        dispatch({
          type: 'deviceLedger/updateState',
          payload: {
            list: [],
            total: 0,
            pageCount: 0,
            allPages: 0,
          }
        })
        dispatch({
          type: 'deviceLedger/updateSerachParams',
          payload: {
            serachParams: {}
          }
        })
      }
    }
  }, [dispatch, pathname])
  useEffect(() => {
    dispatch({
      type: 'deviceLedger/getList',
      payload: {
        current,
        size,
        ...serachParams
      }
    })
  }, [dispatch, current, size, serachParams])
  useEffect(() => {
    if (isRefresh) {
      searchRef.current.resetFields()
    }
  },[isRefresh])
  // 详情
  function toDetail(t) {
    clearDetail();
    router.push({
      pathname: '/deviceLedger/detail',
      query: {
        id: t.id,
      },
    });
  }
  // 编辑
  function toEdit(t) {
    router.push({
      pathname: '/deviceLedger/edit',
      query: {
        id: t.id,
      },
    });
  }
  // 清空详情
  function clearDetail() {
    dispatch({
      type: 'deviceLedger/updateDetail',
      payload: { detail: {} },
    });
  }

  return (
    <KeepAlive name='deviceLedger' when={catchObj.deviceLedger}>
      <div className="deviceLedger">
        <div className="deviceLedger-form">
          <HeadFormRef
            getFormData={v => {
              dispatch({
                type: 'deviceLedger/updateSerachParams',
                payload: {
                  serachParams: {
                    ...v,
                    current: 1
                  }
                }
              })
            }}
            ledgerStatus={ledgerStatus}
            runStatus={runStatus}
            ref={searchRef}
          />
        </div>
        <div className="deviceLedger-table">
          <Button className="btn blue-button" type="primary" onClick={() => router.push('/deviceLedger/add')}>
            新建设备台账
          </Button>
          <Table
            columns={deLedgerCn.list}
            dataSource={list}
            pagination={false}
            className="self-table"
            bordered={true}
            rowKey={(r) => r.id}
          />
          <Paging
            total={total}
            handlePageChange={(c) => {
              dispatch({
                type: 'deviceLedger/updateSerachParams',
                payload: {
                  serachParams: {
                    ...serachParams,
                    current: c
                  }
                }
              })
            }}
            pageSize={10}
            pageCount={pageCount}
            pages={allPages}
          ></Paging>
        </div>
        <DeclareFault
          visible={visible}
          proId={proId}
          cancelDecl={() => { setVisible(false); }}
          pageNations={{
            size: '10',
            current,
          }}
        />
      </div>
    </KeepAlive>
  );
}

export default connect(({ deviceLedger, commonAction }) => ({
  deviceLedger,
  commonAction
}))(withRouter(DeviceLedger));